<template>
    <div class="login-container">
      <el-card class="login-card">
        <h2>登录</h2>
        <el-form :model="loginForm" :rules="rules" ref="loginForm">
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" placeholder="用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="loginForm.password" type="password" placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogin" :loading="loading">登录</el-button>
            <router-link to="/register" class="register-link">没有账号？去注册</router-link>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script>
  export default {
    data() {
      return {
        loginForm: {
          username: '',
          password: ''
        },
        rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ]
        },
        loading: false
      }
    },
    methods: {
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true
            this.$store.dispatch('login', this.loginForm)
              .then(() => {
                this.$message.success('登录成功')
                this.$router.push('/')
              })
              .catch(error => {
                this.$message.error(error.response?.data?.message || '登录失败')
              })
              .finally(() => {
                this.loading = false
              })
          }
        })
      }
    }
  }
  </script>
  
  <style scoped>
  .login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: #f5f5f5;
  }
  .login-card {
    width: 400px;
    padding: 20px;
  }
  .register-link {
    margin-left: 15px;
    color: #409EFF;
    text-decoration: none;
  }
  </style>